package droid.insane.GUI;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import droid.insane.communication.Communicator;
import droid.insane.logic.ConstantValues;
import droid.insane.logic.ExtendedListView;
import droid.insane.logic.PortfolioManager;
import droid.insane.logic.R;
import droid.insane.logic.UpdateFlags;

/**
 * @author Sandamal Displays the data in the portfolio
 */
public class PortfolioWindow extends ListActivity {

	private String[] buyReccomendations;
	private static final int DEFAULT_PORTFOLIO_ID = 1;
	private static ArrayList<String[]> rowList;
	private ExtendedListView mAdapter;
	private double[] headerValues;
	private TextView totalValue;
	private TextView todaysChange;
	private Handler handler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mystocks);

		final ListView lv = getListView();
		registerForContextMenu(lv);
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showCompanyDetails(rowList.get(arg2)[0]);
			}
		});

		rowList = PortfolioManager.getManager().getDataForPortfolio(
				DEFAULT_PORTFOLIO_ID);// retrieves all the rows from the
										// portfolio
		mAdapter = new ExtendedListView(this, rowList, R.layout.listentry);
		setListAdapter(mAdapter);
		totalValue = (TextView) findViewById(R.id.txtv_totalValField);
		todaysChange = (TextView) findViewById(R.id.txtv_todaysChangeField);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Bundle b = msg.getData();
				String[] temp = b.getStringArray("data");
				totalValue.setText(temp[0]);
				if (temp[1].startsWith("-")) {
					todaysChange.setTextColor(Color.RED);
				} else {
					todaysChange.setTextColor(Color.GREEN);
				}
				todaysChange.setText(temp[1] + " (" + temp[2] + "%)");
			}
		};
		updateTextFields();

	}

	/**
	 * @param str
	 *            - symbol of the selected company
	 */
	protected void showCompanyDetails(String str) {
		Intent showProfileIntent = new Intent(getBaseContext(),
				CompanyInfo.class);
		showProfileIntent.putExtra(ConstantValues.SYMBOL, str);
		startActivity(showProfileIntent);

	}

	/**
	 * THis method updates the Total Value and Todays gain text fields
	 */
	private void updateTextFields() {
		Thread t = new Thread() {

			@Override
			public void run() {
				Message message = new Message();
				Bundle b = new Bundle();
				DecimalFormat df = new DecimalFormat("###,###.##");

				headerValues = PortfolioManager.getManager().getTotalValue(
						DEFAULT_PORTFOLIO_ID);
				String total = df.format(headerValues[0]);
				double diff = headerValues[0] - headerValues[1];
				String change = df.format(diff);
				String changePrec = df.format(diff * 100 / headerValues[1]);

				b.putStringArray("data", new String[] { total, change,
						changePrec });
				message.setData(b);
				handler.sendMessage(message);
			}

		};
		t.start();
	}

	/**
	 * updates the display when the database is changed
	 */
	private void updateDisplay() {
		updateTextFields();
		rowList = PortfolioManager.getManager().getDataForPortfolio(
				DEFAULT_PORTFOLIO_ID);
		mAdapter.updateDataset(rowList);
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.portfolio_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.itm_update_data:
			new Communicator(this).execute(new Void[] {});
			updateDisplay();
			return true;

		case R.id.itm_buy:
			addStock();
			return true;

		case R.id.itm_sell:
			Log.d(ConstantValues.TAG, "clicked sell");
			return true;

		default:
			return false;
		}

	}

	/**
	 * When the user wants to add stocks to the portfolio this method is called
	 */
	private void addStock() {
		if (buyReccomendations == null) {
			buyReccomendations = PortfolioManager.getManager()
					.getAllStockNames();
		}

		AlertDialog.Builder addStockDialog = new Builder(this);
		addStockDialog.setTitle(ConstantValues.ADD_STOCK_TITLE);
		addStockDialog.setCancelable(true);
		addStockDialog.setIcon(R.drawable.ic_menu_buy);

		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.buyalertdialog,
				null);
		addStockDialog.setView(textEntryView);

		final EditText edtStock = (EditText) textEntryView
				.findViewById(R.id.ac_stock);
		final EditText edtPrice = (EditText) textEntryView
				.findViewById(R.id.et_price);
		final EditText edtQty = (EditText) textEntryView
				.findViewById(R.id.et_quantity);

		// The positive button is set to Add
		addStockDialog.setPositiveButton("Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int id) {
						try {
							if (edtStock.getText().toString() == ""
									|| edtPrice.getText().toString() == ""
									|| edtQty.getText().toString() == "") {
								Log.d(ConstantValues.TAG, "Invalid Input");
							} else {
								boolean success = PortfolioManager.getManager()
										.addtoPortfolio(DEFAULT_PORTFOLIO_ID,
												edtStock.getText().toString(),
												edtPrice.getText().toString(),
												edtQty.getText().toString());
								updateDisplay();
							}
						} catch (Exception e) {
							updateDisplay();
						}
						;
					}
				});
		// negative button is set to cancel
		addStockDialog.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();

					}
				});

		try {
			AutoCompleteTextView textView = (AutoCompleteTextView) textEntryView
					.findViewById(R.id.ac_stock);
			final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_dropdown_item_1line,
					buyReccomendations);
			textView.setAdapter(adapter);
		} catch (Exception e) {
			Log.e(ConstantValues.TAG, e.getMessage());
		}

		addStockDialog.create();
		addStockDialog.show();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume() When the activity is resumed and the
	 * database has been updated the display is also updated
	 */
	@Override
	protected void onResume() {
		if (UpdateFlags.isPORTFOLIO_FLAG()) {
			updateDisplay();
			UpdateFlags.setPORTFOLIO_FLAG(false);
		}
		super.onResume();
	}
}
